#!/bin/bash
# 多账户交易机器人启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

print_message $BLUE "🚀 多账户交易机器人启动脚本"
echo "=================================="

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    print_message $RED "❌ Python3 未安装"
    exit 1
fi

# 检查依赖
print_message $YELLOW "📦 检查依赖..."
if ! python3 -c "import ccxt, requests, json" &> /dev/null; then
    print_message $YELLOW "⚠️ 缺少依赖，正在安装..."
    pip3 install -r requirements.txt
fi

# 检查配置文件
if [ ! -f "accounts_config.json" ]; then
    print_message $RED "❌ 配置文件 accounts_config.json 不存在"
    exit 1
fi

if [ ! -f ".env" ]; then
    print_message $YELLOW "⚠️ .env 文件不存在，请创建并配置环境变量"
    print_message $YELLOW "参考 .env.example 文件"
    exit 1
fi

# 创建日志目录
mkdir -p logs

# 检查环境变量
print_message $YELLOW "🔍 检查环境变量..."

# 加载环境变量
source .env

# 检查必要的环境变量
required_vars=(
    "DEEPSEEK_API_KEY"
    "OKX_DEMO_API_KEY"
    "OKX_DEMO_SECRET_KEY"
    "OKX_DEMO_PASSPHRASE"
    "TELEGRAM_BOT_TOKEN"
)

missing_vars=()
for var in "${required_vars[@]}"; do
    if [ -z "${!var}" ]; then
        missing_vars+=("$var")
    fi
done

if [ ${#missing_vars[@]} -ne 0 ]; then
    print_message $RED "❌ 缺少必要的环境变量:"
    for var in "${missing_vars[@]}"; do
        echo "   - $var"
    done
    exit 1
fi

print_message $GREEN "✅ 环境检查通过"

# 显示配置信息
print_message $BLUE "📊 配置信息:"
echo "----------------------------------------"
echo "DeepSeek API: ${DEEPSEEK_API_KEY:0:10}..."
echo "OKX Demo API: ${OKX_DEMO_API_KEY:0:10}..."
echo "Telegram Bot: ${TELEGRAM_BOT_TOKEN:0:10}..."
echo "----------------------------------------"

# 选择运行模式
print_message $YELLOW "🎯 选择运行模式:"
echo "1) 本地多账户模式"
echo "2) 本地测试工具"
echo "3) Docker 多账户模式"

read -p "请选择 (1-3): " choice

docker_compose_cmd() {
    if command -v docker &> /dev/null; then
        if docker compose version &> /dev/null; then
            docker compose "$@"
            return
        fi
    fi

    if command -v docker-compose &> /dev/null; then
        docker-compose "$@"
        return
    fi

    print_message $RED "❌ 未检测到 docker 或 docker-compose，请先安装 Docker"
    exit 1
}

case $choice in
    1)
        print_message $GREEN "🚀 启动多账户模式..."
        python3 multi_account_manager.py
        ;;
    2)
        print_message $GREEN "🧪 运行测试工具..."
        python3 test_multi_account.py
        ;;
    3)
        print_message $GREEN "🐳 启动 Docker 多账户模式 (docker-compose.yml)..."
        docker_compose_cmd -f docker-compose.yml up -d multi-account-bot
        print_message $GREEN "✅ Docker 多账户服务已启动，可通过 docker compose ps 查看"
        ;;
    *)
        print_message $RED "❌ 无效选择"
        exit 1
        ;;
esac

print_message $GREEN "✅ 脚本执行完成"
